package com.amin.app.web.controller;

import com.amin.app.web.entity.Page;
import com.amin.app.web.entity.SDep;
import com.amin.app.web.entity.SDict;
import com.amin.app.web.service.DepService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSessionException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class DepController {

    final
    DepService depService;

    public DepController(DepService depService) {
        this.depService = depService;
    }

    /**
     * 获取部门列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/dep/getDepList")
    public String getDepList(Model model, Page page, SDep sDep){
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<SDep> depList = depService.getDepList(sDep);
        PageInfo<SDep> depListPage = new PageInfo<>(depList);
        model.addAttribute("depList",depListPage);
        model.addAttribute("deps",sDep);
        return "amin/dep/depList";
    }
    /**
     * 创建部门/编辑部门
     * @param model
     * @param sDep
     * @return
     */
    @RequestMapping(value = "/dep/createDep")
    public String createDep(Model model, SDep sDep){
        List<SDep> depList = depService.getDepList(sDep);
        model.addAttribute("depList",depList);
        if (null != sDep.getId() && 0 != sDep.getId()){
            sDep = depService.getDepById(sDep.getId());
        }
        model.addAttribute("dep",sDep);
        return "/amin/dep/createDep";
    }

    /**
     * 数据提交
     * @param sDep
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dep/dataSubmit")
    public Map<Object,Object> dataSubmit(SDep sDep){
        Map<Object,Object> answer = new HashMap<>();
        try {
            if (null == sDep.getId() || 0 ==  sDep.getId()){
                sDep.setCreatedTime(new Date());
                depService.save(sDep);
            }else {
                depService.update(sDep);
            }
            answer.put("code",0);
            answer.put("msg","数据保存成功");
        }catch (SqlSessionException e){
            answer.put("code",1);
            answer.put("msg",e.getMessage());
        }
        return answer;
    }

    /**
     * 删除部门
     * @param model
     * @param sDep
     * @return
     */
    @RequestMapping(value = "/dep/delById")
    public String delById(Model model, SDep sDep){
        depService.delById(sDep.getId());
        return "redirect:/dep/getDepList";
    }
}
